﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
 
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using UsualLib;

namespace GameArchiveBak
{
    public partial class Form1 : Form
    {
        #region 声明变量

        /// <summary>
        /// 表示正在加载,在Form Load 尾设置为false;
        /// </summary>
        private bool bFormLoading = false;

        /// <summary>
        /// 当前程序所在目录
        /// </summary>
        string exePath = new DirectoryInfo(Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName).Parent.FullName;


        /// <summary>
        /// 配置文件名
        /// </summary>
        string configXmlFileName = "GABConfig.xml";
        /// <summary>
        /// 配置文件完整路径
        /// </summary>
        string configXmlFileFullName = string.Empty;
        /// <summary>
        /// 数据库文件名
        /// </summary>
        string dbName = "GameDoc.db";
        /// <summary>
        /// 数据库完整路径
        /// </summary>
        string dbFullName = string.Empty;

        /// <summary>
        /// 数据库的操作。
        /// </summary>
        SqliteOper _SqliteOp;

        #endregion

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            dgvMain.AutoGenerateColumns = false;
            lblOpStatus.Text = string.Empty;
            lblAutoBakStatus.Text = string.Empty;

            if (!exePath.EndsWith(@"\"))
            {
                exePath += @"\";
            }
            dbFullName = exePath + dbName;
            //检查数据库
            _SqliteOp = new SqliteOper(dbFullName);
            if (!_SqliteOp.CheckDb())
            {
                MessageBox.Show("创建数据库失败！");
                gbOp.Enabled = false;
                return;
            }
            BindGrid();
        }

        private void BindGrid()
        {
            dgvMain.DataSource = _SqliteOp.GetGameDocList();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            frmAdd frm = new frmAdd();
            frm.FormAcessMode = EnumClass.FormAcessMode.Add;
            frm.ShowDialog();
            if (frm.DialogResult == DialogResult.OK)
            {
                //检查是否包含在特殊目录中
                bool bIsSpec = false;
                string specDirName = string.Empty;
                string outputPath = string.Empty;
                IsSpecDir(frm.SourcePath, out bIsSpec, out specDirName, out outputPath);

                _SqliteOp.InsertGameDoc(Guid.NewGuid().ToString(), frm.DocDescr, outputPath, frm.TargetPath, "", bIsSpec, specDirName);

                BindGrid();
            }
        }

        /// <summary>
        /// 判断是否包含特殊目录。inputPath 要判断的目录。bIsSpec 是否包含特殊目录。specDirName 特殊目录名称。outputPath 去除特殊目录的部分。
        /// </summary>
        /// <param name="inputPath"></param>
        /// <param name="bIsSpec"></param>
        /// <param name="specDirName"></param>
        /// <param name="outputPath"></param>
        public void IsSpecDir(string inputPath, out bool bIsSpec, out string specDirName, out string outputPath)
        {

            bIsSpec = false;
            specDirName = string.Empty;
            outputPath = inputPath;
            IList<string> lstsf = Enum.GetNames(typeof(Environment.SpecialFolder));
            foreach (string sf in lstsf)
            {
                Environment.SpecialFolder sfType = (Environment.SpecialFolder)Enum.Parse(typeof(Environment.SpecialFolder), sf);
                string specDir = Environment.GetFolderPath(sfType);
                if (string.IsNullOrEmpty(specDir))
                {
                    continue;
                }
                if (inputPath.ToLower().Contains(specDir.ToLower()))
                {
                    bIsSpec = true;
                    specDirName = sf;
                    outputPath = inputPath.ToLower().Replace(specDir.ToLower(), "");
                    break;
                }
            }
        }

        /// <summary>
        /// 按名字获取特殊目录的路径。
        /// </summary>
        /// <param name="specDirName"></param>
        /// <returns></returns>
        private string GetSpecDirValue(string specDirName)
        {
            string tmp = "";

            Environment.SpecialFolder sfType = (Environment.SpecialFolder)Enum.Parse(typeof(Environment.SpecialFolder), specDirName);
            tmp = Environment.GetFolderPath(sfType);

            return tmp;
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnEdit_Click(object sender, EventArgs e)
        {
            if (dgvMain.Rows.Count > 0)
            {
                string sourcePath = dgvMain.Rows[dgvMain.CurrentCell.RowIndex].Cells["co_DocSource"].Value.ToString();
                string sourcePathFull = sourcePath;
                bool bIsSpec = false;
                string specDirName = string.Empty;
                string outputPath = string.Empty;

                string editId = dgvMain.Rows[dgvMain.CurrentCell.RowIndex].Cells["co_gdid"].Value.ToString();
                string targetFull = dgvMain.Rows[dgvMain.CurrentCell.RowIndex].Cells["co_DocTargetFull"].Value.ToString();
                if (dgvMain.Rows[dgvMain.CurrentCell.RowIndex].Cells["co_IncludeSpecDir"].Value.ToString().ToLower() == "true")
                {
                    specDirName = dgvMain.Rows[dgvMain.CurrentCell.RowIndex].Cells["co_SpecDirName"].Value.ToString();
                    string tmpSource = GetSpecDirValue(specDirName);
                    sourcePathFull = tmpSource + sourcePath;
                }

                frmAdd frm = new frmAdd();
                frm.FormAcessMode = EnumClass.FormAcessMode.Edit;
                frm.DocDescr = dgvMain.Rows[dgvMain.CurrentCell.RowIndex].Cells["co_DocDescr"].Value.ToString();
                frm.SourcePath = sourcePathFull;
                frm.TargetPath = dgvMain.Rows[dgvMain.CurrentCell.RowIndex].Cells["co_DocTarget"].Value.ToString();
                frm.ShowDialog();

                if (frm.DialogResult == DialogResult.OK)
                {
                    //检查是否包含在特殊目录中

                    IsSpecDir(frm.SourcePath, out bIsSpec, out specDirName, out outputPath);

                    _SqliteOp.UpdateGameDoc(editId, frm.DocDescr, outputPath, frm.TargetPath, targetFull, bIsSpec, specDirName);

                    BindGrid();
                }
            }
        }

        /// <summary>
        /// 根据源目录是否包含特殊目录产生源目录完整路径。
        /// </summary>
        /// <param name="dgvr"></param>
        /// <returns></returns>
        private string GenSourcePathFull(DataGridViewRow dgvr)
        {
            string sourcePath = dgvr.Cells["co_DocSource"].Value.ToString();
            string sourcePathFull = sourcePath;
            if (dgvr.Cells["co_IncludeSpecDir"].Value.ToString().ToLower() == "true")
            {
                string specDirName = dgvr.Cells["co_SpecDirName"].Value.ToString();
                string tmpSource = GetSpecDirValue(specDirName);
                sourcePathFull = tmpSource + sourcePath;
            }
            return sourcePathFull;
        }

        private void btnDel_Click(object sender, EventArgs e)
        {
            if (dgvMain.Rows.Count > 0)
            {
                if (MessageBox.Show("确定删除？", "", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    string editId = dgvMain.Rows[dgvMain.CurrentCell.RowIndex].Cells["co_gdid"].Value.ToString();
                    if (_SqliteOp.DeleteGameDoc(editId))
                    {
                        lblOpStatus.Text = "删除成功！";
                        dgvMain.Rows.RemoveAt(dgvMain.CurrentCell.RowIndex);
                    }
                    else
                    {
                        lblOpStatus.Text = "删除失败！";
                    }
                }
            }
        }

        private void btnBak_Click(object sender, EventArgs e)
        {
            if (dgvMain.Rows.Count == 0)
                return;

            if (MessageBox.Show("确定备份？", "", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                BakMethod(dgvMain.Rows[dgvMain.CurrentCell.RowIndex]);                 

                lblOpStatus.Text = "备份完成！";                 
            }
        }

        private void btnRestore_Click(object sender, EventArgs e)
        {
            if (dgvMain.Rows.Count == 0)
                return;

            if (MessageBox.Show("确定还原？", "", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                string editId = dgvMain.Rows[dgvMain.CurrentCell.RowIndex].Cells["co_gdid"].Value.ToString();
                //检查源目录
                string sourcePath = GenSourcePathFull(dgvMain.Rows[dgvMain.CurrentCell.RowIndex]);
                if (!Directory.Exists(sourcePath))
                {
                    Directory.CreateDirectory(sourcePath);
                    MessageBox.Show(string.Format("源目录 {0} 不存在！ 现已创建!", sourcePath));
                    return;
                }
                //如果目标目录不存在
                string targetFullPath = dgvMain.Rows[dgvMain.CurrentCell.RowIndex].Cells["co_DocTargetFull"].Value.ToString();                 
                if (!Directory.Exists(targetFullPath))
                {
                    MessageBox.Show("目标目录不存在！");
                    return;
                }

                UDirCopy.DirCopy(targetFullPath, sourcePath, true);                

                lblOpStatus.Text = "还原完成！"+DateTime.Now.ToString();
                 
            }
        }

        private void btnBakAll_Click(object sender, EventArgs e)
        {
            if (dgvMain.Rows.Count == 0)
                return;

            if (MessageBox.Show("确定备份？", "", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                foreach(DataGridViewRow dgvr in dgvMain.Rows)
                {
                    BakMethod(dgvr);
                }
                lblOpStatus.Text = "备份完成！";
            }
        }

        /// <summary>
        /// 备份
        /// </summary>
        /// <param name="dgvr"></param>
        private void BakMethod(DataGridViewRow dgvr)
        {
            string editId = dgvr.Cells["co_gdid"].Value.ToString();
            string strDocDesc = dgvr.Cells["co_DocDescr"].Value.ToString();
            //检查源目录
            string sourcePath = GenSourcePathFull(dgvr);
            if (!Directory.Exists(sourcePath))
            {
                MessageBox.Show("源目录不存在！");
                return;
            }
            //如果目标目录不存在，创建
            string targetPath = dgvr.Cells["co_DocTarget"].Value.ToString();
            if (!Directory.Exists(targetPath))
                Directory.CreateDirectory(targetPath);
            if (!targetPath.EndsWith(@"\"))
                targetPath += @"\";
            string targetFullPath = targetPath + strDocDesc + editId;
            if (!Directory.Exists(targetFullPath))
                Directory.CreateDirectory(targetFullPath);

            UDirCopy.DirCopy(sourcePath, targetFullPath, true);

            _SqliteOp.UpdateTargetPathFull(editId, targetFullPath);
            
            //更新界面
            dgvr.Cells["co_DocTargetFull"].Value = targetFullPath;
        }
    }
}
